/*
 * h_cc2640r2f_adc.c
 *
 *  Created on: Sep 3, 2020
 *      Author: hemingway
 */
#include "h_cc2640r2f_adc.h"
#include <ti/drivers/ADC.h>
#include "board.h"

#include <stdio.h>
#include <string.h>

//static ADC_Handle ADCHandle;

signed int H_CC2640R2F_ADC_Read(void)
{
    ADC_Handle   ADCHandle;
    ADC_Params   ADCparams;
    int_fast16_t res;

//        unsigned int adcValue0MicroVolt = 0U;
    unsigned short adcValue0 = 0U;

    ADC_Params_init(&ADCparams);
    ADCHandle = ADC_open(CC2640R2_LAUNCHXL_ADC0, &ADCparams);

    if (ADCHandle == NULL)
    {
        printf("Error initializing ADC channel 0\n");
        return (-1);
    }
    else
    {
        res = ADC_convert(ADCHandle, &adcValue0);

        ADC_close(ADCHandle);

        if (res == ADC_STATUS_SUCCESS)
        {
            ADC_close(ADCHandle);
            return adcValue0;
        }
        else {
            return (-1);
        }
    }
}

unsigned int H_CC2640R2F_ADC_Read_MicroVolts_byNum(unsigned char adc_num)
{
    ADC_Handle   ADCHandle;
    ADC_Params   ADCparams;
    int_fast16_t res;

    unsigned int adcValue0MicroVolt = 0U;
    unsigned short adcValue0 = 0U;

    ADC_Params_init(&ADCparams);
    switch(adc_num)
    {
        case 0:
            ADCHandle = ADC_open(CC2640R2_LAUNCHXL_ADC7, &ADCparams);
            break;

        case 1:
            ADCHandle = ADC_open(CC2640R2_LAUNCHXL_ADC5, &ADCparams);
            break;

        case 2:
            ADCHandle = ADC_open(CC2640R2_LAUNCHXL_ADC6, &ADCparams);
            break;

        default:
            break;
    }
    

    if (ADCHandle == NULL)
    {
        printf("Error initializing ADC channel %d\n", adc_num);
        return (0);
    }
    else
    {
        res = ADC_convert(ADCHandle, &adcValue0);

        ADC_close(ADCHandle);

        if (res == ADC_STATUS_SUCCESS)
        {
            adcValue0MicroVolt = ADC_convertRawToMicroVolts(ADCHandle, adcValue0);
            ADC_close(ADCHandle);
            return adcValue0MicroVolt;
        }
        else
        {
            ADC_close(ADCHandle);
            return (0);
        }
    }
}

signed char H_CC2640R2F_ADC_Init(void)
{
//    ADC_Params ADCparams;
//    ADC_init();
//    ADC_Params_init(&ADCparams);
//    ADCHandle = ADC_open(CC2640R2_LAUNCHXL_ADC0, &ADCparams);
//    if (ADCHandle != NULL)
//    {
//        ADC_close(ADCHandle);
//        return (-1);
//    }
    ADC_init();

    return 0;
}
